﻿using SQLDeploy.Data.Connections;
using SQLDeploy.Data.Deployment.Steps.Tasks;
using SQLDeploy.Execution.Internal;
using SQLDeploy.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;

namespace SQLDeploy.Execution.Deployment.Steps.Tasks
{
    public class SQLScriptTask_Executor : SQLScriptTask, ITaskExecutor
    {
        private Data.Environments.Environment _Environment = null;

        public SQLScriptTask_Executor(SQLScriptTask TaskData) :
            base(TaskData.ParentStep)
        {
            base.ConnectionName = TaskData.ConnectionName;
            base.Name = TaskData.Name;
            base.ReplicatedOnly = TaskData.ReplicatedOnly;
            base.Script = TaskData.Script;
        }

        public void setEnvironment(Data.Environments.Environment executionEnvironment)
        {
            Check.notNull(_Environment, "ExecutionEnvironment");
            _Environment = executionEnvironment;
        }

        public List<_BaseConnection> getConnection()
        {
            if (_Environment == null)
                throw new ArgumentException("Must set Environment before calling getConnection.");
            return _Environment.getConnectionsByName(this.ConnectionName);
        }

        public bool PerformPreExecutionValidation()
        {
            //this.CurrentStatus = TaskStatus.Validating;
            bool retVal = true;
            try
            {
                if (_Environment == null)
                    throw new ArgumentException("Must set Environment before calling PerformPreExecutionValidation.");

                retVal = Common.PerformCommonTaskExectorValidation(this, _Environment);
                if (retVal)
                {
                    //TODO add additional SQL checks here, maybe parsing the script, 
                    //maybe hooking in external checks???  TBD
                }
                
            }
            catch (Exception e)
            {
                Trace.TraceError(TaskNameHeader + "EXCEPTION: " + e.ToString());
                retVal = false;
            }
            finally
            {
                //this.CurrentStatus = TaskStatus.Idle;
            }
            //If we reached here take the retVal;
            return retVal;
        }

        public TaskExecutionResult ExecuteTask()
        {
            throw new NotImplementedException();
        }

        public Type RequiredConnectionType()
        {
            return typeof(_BaseSQLConnection);
        }

    }
}
